package com.hbnu.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hbnu.system.config.BaseException;
import com.hbnu.system.mapper.ArtMapper;
import com.hbnu.system.mapper.ArtQualificationMapper;
import com.hbnu.system.model.context.BaseContext;
import com.hbnu.system.model.dto.ArtDTO;
import com.hbnu.system.model.entity.Art;
import com.hbnu.system.model.entity.Art_Qualification;
import com.hbnu.system.model.entity.Art_author;
import com.hbnu.system.model.entity.User;
import com.hbnu.system.service.*;
import com.hbnu.system.utils.CheckRoleUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.List;
import java.util.Objects;

@Service
public class ArtQualificationServiceImpl extends ServiceImpl<ArtQualificationMapper, Art_Qualification> implements IArtQualificationService {
    @Autowired
    private IArtTypeService iArtTypeService;

    @Autowired
    private IArtService iArtService;

    @Autowired
    private ArtMapper artMapper;

    @Autowired
    private IUserService iUserService;
    
    @Autowired
    private IArtauthorService iArtauthorService;

    @Autowired
    private IArtQualificationService iArtQualificationService;

    @Autowired
    private CheckRoleUtil checkRoleUtil;

    private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("0.00");

    @Override
    public boolean addArt_Qualification(Art_Qualification art_qualification) {
        System.out.println("art_q="+art_qualification);

        // 判断该艺术成果是否已有量化分数
        List<Art_Qualification> existingQualifications = iArtQualificationService.list(
                Wrappers.lambdaQuery(Art_Qualification.class)
                        .eq(Art_Qualification::getArtID, art_qualification.getArtID())
        );
        if (existingQualifications != null && !existingQualifications.isEmpty()) {
            throw new BaseException("该艺体成果已有量化分数，不可重复添加");
        }

        Art p1=iArtService.getArt(art_qualification.getArtID());
        checkRoleUtil.checkPermissionAchievement(p1.getStatus());

        Art art=iArtService.getArt(art_qualification.getArtID());
        String scoreStr = DECIMAL_FORMAT.format(art_qualification.getFinalValue());
        art.setScore(scoreStr);
        System.out.println("art="+art);
        iArtService.updateById(art);

        String Pscore = "0.00";
        // 9. 修改著作作者的个人得分
        String artid=art_qualification.getArtID();
        List<Art_author> artauthorList = iArtauthorService.listAuthor(artid);
        System.out.println("artauthorList="+artauthorList);
        String userId = BaseContext.getCurrentId();
        User user = iUserService.getById(userId);

        if (artauthorList != null && !artauthorList.isEmpty()) {
            // 如果只有一个作者且是当前用户，则不需要更新作者信息
            if (artauthorList.size() == 1) {
                Art_author soleAuthor = artauthorList.get(0);
                if (Objects.equals(soleAuthor.getUserAccount(), user.getAccount())) {
                    System.out.println("只有一个作者且是当前用户，不更新作者信息");
                    return baseMapper.insert(art_qualification) > 0;
                }
            }

            // 执行作者信息更新操作
            for (Art_author author : artauthorList) {
                // 确保不更新当前用户自己的信息
                if (!Objects.equals(author.getUserAccount(), user.getAccount())) {
                    iArtauthorService.updateArtAuthor(author);
                    System.out.println("更新作者: " + author.getUserAccount());
                } else {
                    System.out.println("跳过当前用户: " + author.getUserAccount());
                }
            }
        }

//        if (artauthorList != null && !artauthorList.isEmpty()) {
//            boolean shouldUpdate = true;
//            if (artauthorList.size() == 1) {
//                Art_author soleAuthor = artauthorList.get(0);
//                if (Objects.equals(soleAuthor.getUserAccount(), user.getAccount())) {
//                    shouldUpdate= false;
//                }
//            }
//            // 执行更新操作
//            if (shouldUpdate) {
//                for (Art_author author : artauthorList) {
//                    iArtauthorService.updateArtAuthor(author);
//                }
//            }
//        }

        return baseMapper.insert(art_qualification) > 0;
        
//        return baseMapper.insert(art_qualification) == 1;
    }


    @Override
    public boolean deleteArt_Qualification(String ArtQualificationID) {
        Art_Qualification art_qualification=baseMapper.selectById(ArtQualificationID);
        Art p1=iArtService.getArt(art_qualification.getArtID());

        checkRoleUtil.checkPermissionAchievement(p1.getStatus());
        if (Objects.isNull(art_qualification)){
            throw new BaseException("量化编号有误");
        }
        ArtDTO artdto = iArtService.getArtDTOByID(art_qualification.getArtID());
        artdto.setScore(0);
        Art art=new Art();
        BeanUtils.copyProperties(artdto,art);
        System.out.println("art="+art);

        UpdateWrapper<Art> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("ArtID", art.getArtID())
                .set("score", 0);

// 执行更新，会忽略实体对象中的值，直接使用wrapper中的设置
        iArtService.update(updateWrapper);

//        iArtService.updateById(art);

        List<Art_author> artauthorList = iArtauthorService.listAuthor(art.getArtID());
        String userId = BaseContext.getCurrentId();
        User user = iUserService.getById(userId);
        if (artauthorList != null && !artauthorList.isEmpty()) {
            boolean shouldUpdate = true;
            if (artauthorList.size() == 1) {
                Art_author soleAuthor = artauthorList.get(0);
                if (Objects.equals(soleAuthor.getUserAccount(), user.getAccount())) {
                    shouldUpdate= false;
                }
            }
            // 执行更新操作
            if (shouldUpdate) {
                for (Art_author author : artauthorList) {
                    iArtauthorService.updateArtAuthor(author);
                }
            }
        }
        
        return baseMapper.deleteById(ArtQualificationID) == 1;

    }

    @Override
    public List<Art_Qualification> getOneArt_Qualification(String ArtID) {
        Art art = iArtService.getArt(ArtID);
        if(Objects.isNull(art)){
            throw new BaseException("艺体编号有误!");
        }

        List<Art_Qualification> art_qualifications = baseMapper.selectList(Wrappers.lambdaQuery(Art_Qualification.class)
                .eq(Art_Qualification::getArtID, ArtID));
        return art_qualifications;
    }

    /**
     * 更新分数
     * @param artQualification
     * @return
     */
    @Override
    public boolean upArtScore(Art_Qualification artQualification) {
//        Art p1=iArtService.getArt(artQualification.getArtQualificationID());
        Art_Qualification art_qualification=baseMapper.selectById(artQualification);
        Art p1=iArtService.getArt(art_qualification.getArtID());
        checkRoleUtil.checkPermissionAchievement(p1.getStatus());
        Art_Qualification a = baseMapper.selectOne(Wrappers.lambdaQuery(Art_Qualification.class)
                .eq(Art_Qualification::getArtQualificationID, artQualification.getArtQualificationID()));
        a.setFinalValue(artQualification.getFinalValue());

        Art art = artMapper.selectOne(Wrappers.lambdaQuery(Art.class)
                .eq(Art::getArtID, artQualification.getArtID()));

        String scoreStr = DECIMAL_FORMAT.format(artQualification.getFinalValue());

        art.setScore(scoreStr);
        iArtService.updateArt(art);

        String Pscore = "0.00";
        // 9. 修改著作作者的个人得分
        String artid=art_qualification.getArtID();
        List<Art_author> artauthorList = iArtauthorService.listAuthor(artid);
        String userId = BaseContext.getCurrentId();
        User user = iUserService.getById(userId);
        if (artauthorList != null && !artauthorList.isEmpty()) {
            boolean shouldUpdate = true;
            if (artauthorList.size() == 1) {
                Art_author soleAuthor = artauthorList.get(0);
                if (Objects.equals(soleAuthor.getUserAccount(), user.getAccount())) {
                    shouldUpdate= false;
                }
            }
            // 执行更新操作
            if (shouldUpdate) {
                for (Art_author author : artauthorList) {
                    iArtauthorService.updateArtAuthor(author);
                }
            }
        }

//        return baseMapper.insert(art_qualification) > 0;

        return baseMapper.updateById(artQualification) == 1;
    }

}
